package com.visikard.ui.fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.CreateCouponAsyncTask;
import com.visikard.item.CreateCouponParams;
import com.visikard.response.CreateCpResponse;
import com.visikard.ui.R;
import com.visikard.ui.activity.CouponBuilderActivityV3;
import com.visikard.ui.activity.CouponCameraPreviewActivity;
import com.visikard.utility.ScalingUtilities;
import com.visikard.utility.ScalingUtilities.ScalingLogic;
import com.visikard.utility.Utils;

public class CouponPreviewFragment extends BaseFragment {
	// setArguments-->onAttach-->onCreate-->onCreateView-->onActivityCreated
	// onDestroyView-->onDestroy-->onDetach
	private CouponBuilderActivityV3 me;

	private ImageView mImageView_coupon;
	private TextView mTextView_name, mTextView_percent, mTextView_expire_date;
	private Button mButton_back, mButton_save;
	private CheckBox mCheckBox_termOfUse;
	private View mView;
	private CreateCouponParams params;
	private BaseTask mAsyncTask;

	public void setParams(CreateCouponParams params) {
		this.params = params;
	}

	public CreateCouponParams getParams() {
		return params;
	}

	private void initControls(View view) {

		mImageView_coupon = (ImageView) view.findViewById(R.id.coupon_image);
		mTextView_name = (TextView) view.findViewById(R.id.name);
		mTextView_percent = (TextView) view.findViewById(R.id.percent_off);
		mTextView_expire_date = (TextView) view.findViewById(R.id.expire_date_Value);

		mButton_back = (Button) view.findViewById(R.id.btn_back);
		mButton_save = (Button) view.findViewById(R.id.btn_save);

		mCheckBox_termOfUse = (CheckBox) view.findViewById(R.id.chk_confirm);
		mCheckBox_termOfUse.setOnCheckedChangeListener(new MyOnCheckChangedListener());

		mButton_back.setOnClickListener(new MyOnClickListener());
		mButton_save.setOnClickListener(new MyOnClickListener());

	}

	@Override
	public void setArguments(Bundle args) {
		// TODO Auto-generated method stub
		super.setArguments(args);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		me = (CouponBuilderActivityV3) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.coupon_preview_activity, null);
		initControls(mView);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		savedInstanceState = getArguments();
		if (savedInstanceState == null)
			return;

		String cpName = savedInstanceState.getString("name");
		String percent = savedInstanceState.getString("percent");
		String cpMax = savedInstanceState.getString("cpmax");
		String des = savedInstanceState.getString("des");
		String address = savedInstanceState.getString("address");
		String lat = savedInstanceState.getString("lat");
		String lon = savedInstanceState.getString("lon");
		String location = generateJson(lat, lon, address);
		String sdate = savedInstanceState.getString("sdate");
		String expireDate = savedInstanceState.getString("edate");
		String timeZone = Utils.getTimeZoneString();

		CreateCouponParams params = new CreateCouponParams();
		saveCoupon(params, cpName, percent, cpMax, des, location, sdate, expireDate, timeZone, 1, expireDate);

		mTextView_name.setText(cpName);
		mTextView_percent.setText(percent + "%");
		mTextView_expire_date.setText(expireDate);

		try {
			Bitmap bitmap = (Bitmap) VKRegApplication.instance.getData(CouponCameraPreviewActivity.CROPPED_BITMAP);
			if (bitmap != null) {
				Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(bitmap, bitmap.getWidth(),
						bitmap.getHeight(), ScalingLogic.CROP);
				if (scaledBitmap != null) {
					// bitmap.recycle();
					mImageView_coupon.setImageBitmap(scaledBitmap);
				}
			}
		}
		catch (NullPointerException e) {
			// TODO: handle exception
		}

	}

	private class MyOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == mButton_back) {
				FragmentManager fm = getActivity().getSupportFragmentManager();
				fm.popBackStack();
			}
			else if (v == mButton_save) {
				if (mCheckBox_termOfUse.isChecked()) {
					createCoupon();

				}

			}
		}
	}

	private void saveCoupon(CreateCouponParams params, String name, String percent, String cpMax, String des,
			String location, String sdate, String edate, String timezone, int enable, String expire) {
		params.setCpName(name);
		params.setCpPercentOff(Integer.parseInt(percent));
		params.setCpMaxOff(Integer.parseInt(cpMax));
		params.setCpDescription(des);
		params.setCpLocation(location);
		params.setCpStartDate(sdate);
		params.setCpEndDate(edate);
		params.setCpTimeZone(timezone);
		params.setCpEnable(1);
		params.setCpExpireDate(expire);
		setParams(params);
	}

	@Override
	protected boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		if (getActivity() == null)
			return false;
		switch (msg.what) {

			case UIMessage.MSG_CREATE_COUPON_FINISH:
				CreateCpResponse result = (CreateCpResponse) msg.obj;
				if (result != null) {
					Log.e(">getErrorCode>", result.getErrorCode() + "");
					if (result.getErrorCode() == 0) {
						int cId = result.getCouponId();
						Log.e("CreateCoupon>", cId + "");
						if (cId > 0) {
							Utils.showToast(me, me.getString(R.string.txt_create_cp_success));

							me.setResult(me.RESULT_OK);
							me.finish();
						}

					}
					else if (result.getErrorCode() == -2) {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.network_problem));
					}
					else if (result.getErrorCode() == -3) {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.txt_create_cp_fail));
					}
					else if (result.getErrorCode() == -4) {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.txt_create_cp_fail));
					}
					else {
						Log.e("CreateCoupon>", result.getErrorMsg());
						Utils.showToast(me, me.getString(R.string.unknown_problem));

					}

				}
				return true;

		}
		return super.handleMessage(msg);
	}

	private void createCoupon() {
		CreateCouponParams params = getParams();
		long fkUser = VKRegApplication.merchantAccountObj.getIdUsers();
		long idUserMerchant = VKRegApplication.merchantAccountObj.getIdUsersMerchant();
		String pathFile_ = Utils.decodeBitmapToFile(
				(Bitmap) VKRegApplication.instance.getData(CouponCameraPreviewActivity.CROPPED_BITMAP), me);
		if (pathFile_ != null && !pathFile_.equals("")) {

			mAsyncTask = new CreateCouponAsyncTask(mHandler, params);
			mAsyncTask.execute(pathFile_, String.valueOf(fkUser), String.valueOf(idUserMerchant));
		}
		else {
			String pathFile = VKRegApplication.instance.getData("path").toString();
			mAsyncTask = new CreateCouponAsyncTask(mHandler, params);
			mAsyncTask.execute(pathFile, String.valueOf(fkUser), String.valueOf(idUserMerchant));
		}

	}

	private class MyOnCheckChangedListener implements OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			if (buttonView.isChecked()) {
				buttonView.setChecked(true);
			}
			else {
				buttonView.setChecked(false);
			}
		}

	}

	private String generateJson(String lat, String lon, String address) {

		try {
			JSONArray array = new JSONArray();
			JSONObject json = new JSONObject();
			json.put("latitude", lat);
			json.put("longitude", lon);
			json.put("address", address);
			array.put(json);
			return array.toString();
		}
		catch (JSONException e) {
			// TODO: handle exception
		}
		return null;

	}

	/**
	 * 
	 */
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}
}
